package com.atguigu.MyTest;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.List;

/**
 * @author haoranlu
 * @project IntelliJ IDEA
 */
public abstract class BasicDAO<T> {
    private Class<T> type;
    private QueryRunner qr = new QueryRunner();
    public BasicDAO() {
        Class<? extends BasicDAO> clazz = this.getClass();
        Type t = clazz.getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        Type[] types = pt.getActualTypeArguments();
        type =(Class<T>) types[0];

    }
    public int update(String sql,Object...params) throws SQLException {
        int count = 0;
        try {
            count = qr.update(JDBCTools.getConnction(), sql, params);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return count;
    }
    public T getBean(String sql,Object...params){
        T t = null;
        try {
            t = qr.query(JDBCTools.getConnction(), sql, new BeanHandler<>(type), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return t;
    }
    public List<T> getBeanList(String sql,Object...params){
        List<T> list=null;
        try {
            list = qr.query(JDBCTools.getConnction(), sql, new BeanListHandler<>(type), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return list;
    }
    public Object getObject(String sql,Object...params){
        Object obj = null;
        try {
            obj = qr.query(JDBCTools.getConnction(), sql, new ScalarHandler<>(), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return obj;
    }
    public void batchUpdate(String sql,Object[][]...params){
        try {
            int[] batch = qr.batch(JDBCTools.getConnction(), sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
